package com.ocom.ugcapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.AcpService;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.card.EntityXfRecord;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.card.EntityXfSubAccount;
import com.ocom.common.entity.company.EntityCompanyConfig;
import com.ocom.common.entity.payconfig.EntityRechargeRule;
import com.ocom.common.entity.payconfig.FeeItem;
import com.ocom.common.enums.OpTypeDiffEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.callpackage.AddPackagePayRequest;
import com.ocom.common.request.payhandle.StaticCodePayRequest;
import com.ocom.common.resp.RespMachMessage;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.pay.CallBackVo;
import com.ocom.common.vo.pay.CheckVo;
import com.ocom.common.vo.pay.ServiceChargesVo;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.common.vo.ugcapi.StaticCodePayVo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.ugcapi.client.*;
import com.ocom.ugcapi.mq.product.ActiveQuiryProduct;
import com.ocom.ugcapi.mq.product.CallbackProducer;
import com.ocom.ugcapi.mq.product.SignProducer;
import com.ocom.ugcapi.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;

@Slf4j
@Service
@RefreshScope
public class PayServiceImpl implements PayService {

	@Value("${paycenter.url}")
	private String payCenterUrl;

	@Resource
	private RedisUtil redisUtil;


	@Autowired
	CompanyClientService companyClientService;

	@Autowired
	EmqxClientService emqxClientService;

	private  static Map<Integer , String> payCenter = new HashMap(){
		{
			put(0, "http://127.0.0.1:8080/ocom_pay/");
			put(1, "http://192.168.3.123:32880/ocom_pay/");
			put(2, "http://192.168.185.142:33880/ocom_pay/");
		}
	};


	@Autowired
	HumanClientService humanClientService;
	@Autowired
	XfRecodeClientService xfRecodeClientService;

	@Autowired
	private PayConfigClientService payConfigClientService;

	@Autowired
	private PayHandleClientService payHandleClientService;

	@Autowired
	ActiveQuiryProduct activeQuiryProduct;

	@Autowired
	CallbackProducer callbackProducer;

	@Autowired
	SignProducer signProducer;


	@Override
	public Result Pay(GzhUserInfo userInfo, Integer amount, Integer type, Integer consState, Integer feeDataId, Integer subAccount) {
		Gson gson=new Gson();

		//1、获取支付通道
		Integer merchId = 0;
		Integer consStateType = 10; //1，充值 10 2缴费 111，112退费   默认1
		String prefix = "CZ";
		if (111 == consState) {
			Result feeResult = payConfigClientService.findByFeeDataId(userInfo.getComId(), feeDataId);
			if (200 == feeResult.getCode() && null != feeResult.getData()) {
				FeeItem feeItem = JSON.parseObject(JSON.toJSONString(feeResult.getData()),FeeItem.class);
				merchId = feeItem.getAccountId();
				//半小时
				boolean lock = redisUtil.lock("feeDataPayLock#comId:" + userInfo.getComId() + "#feeDataId:" + feeDataId, 900);
				if (!lock) {
					return ResultUtil.error(ResultEnum.Err_2046);
				}
			}
			consStateType = 111;
			prefix = "JF";
		}

		if (subAccount > 0) {
			Result result2 = payConfigClientService.getSubAccountList(userInfo.getComId().intValue());
//			System.out.println(result2);
			if (result2.getData() != null) {
				List<EntityXfSubAccount> entityXfSubAccountList = JSON.parseArray(JSON.toJSONString(result2.getData()), EntityXfSubAccount.class);
				boolean flag = false;
				for (EntityXfSubAccount entityXfSubAccount : entityXfSubAccountList) {
					if (entityXfSubAccount.getSubAccount().equals(subAccount)) {
						merchId = entityXfSubAccount.getMerchId();
						flag = true;
						break;
					}
				}
				if (!flag) {
					return ResultUtil.error(ResultEnum.Err_3106);
				}
			} else {
				return ResultUtil.error(ResultEnum.Err_3106);
			}
		}

		Result result = payConfigClientService.MerchPageInfo(userInfo.getComId(), merchId);
		log.info("公众号支付-获取支付通道参数 【{}】",result);
        if(result.getCode()!=200){
            log.info("支付参数获取失败 【{}】 ", result);
            return ResultUtil.error(ResultEnum.Err_4023);
        }

        EntityXfMerchantInfo entityXfMerchantInfo = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),EntityXfMerchantInfo.class);

        //2.预下单

		//获取用户信息
		Result result22 = humanClientService.getXfUserInfo(userInfo.getComId(),userInfo.getPId());
		log.info("公众号支付-支付人员信息 【{}】 ", result22);
		if(result22.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_4023);
		}

		//判断预下单 or 代扣
		XfUserInfoVo xfUserInfoVo=gson.fromJson(gson.toJson(result22.getData()),XfUserInfoVo.class);

		if(type==1){
			//判断公众号支付是否自身的
			if(!userInfo.getFlag()){
				return ResultUtil.error(ResultEnum.Err_3045);
			}
		}


		//补贴金额
		Integer subMoney  =  0 ;
		//赠送、扣减金额
		Integer addMoney  =  0 ;


		//计算补贴等
		try {
			Result result1 = payConfigClientService.getRechargeRule(userInfo.getComId(),subAccount);
			if(result1.getCode()==200){
				List<EntityRechargeRule> list = JSONObject.parseArray(JSON.toJSONString(result1.getData()),EntityRechargeRule.class);

				EntityRechargeRule entityRechargeRuleFirst =null;
				List<Integer>  listMoney = new ArrayList<>();
				for (EntityRechargeRule entityRechargeRule : list){
					if(entityRechargeRule.getRuleNo() == 1) {
						entityRechargeRuleFirst = entityRechargeRule;
					}else{
						listMoney.add(entityRechargeRule.getRecharge());
					}
				}

				/**
				 * discountMode	方式	int	0：无优惠，
				 * 1：按金额赠送，2：按比例赠送，3：按金额补贴，4按比例补贴
				 * 11：按金额扣减，12：按比例扣减
				 */

				//规则内或者自定义最大金额
				if(listMoney.contains(amount)){
					for (EntityRechargeRule entityRechargeRule : list){
						if(entityRechargeRule.getRuleNo() == 1) continue;
						if(entityRechargeRule.getRecharge().equals(amount)){
							BigInteger a=new BigInteger(String.valueOf(entityRechargeRule.getDValue()));
							BigInteger b=new BigInteger(String.valueOf(100));
							BigInteger c=new BigInteger(String.valueOf(amount));
							BigInteger d=a.multiply(c);
							//舍去取整
							BigInteger e=d.divide(b);

							if(entityRechargeRule.getDMode()==1){
								addMoney = entityRechargeRule.getDValue();
							}
							if(entityRechargeRule.getDMode()==2){
								addMoney = e.intValue();
							}
							if(entityRechargeRule.getDMode()==3){
								subMoney = entityRechargeRule.getDValue();
							}
							if(entityRechargeRule.getDMode()==4){
								subMoney = e.intValue();
							}
							if(entityRechargeRule.getDMode()==11){
								addMoney = -1 *  entityRechargeRule.getDValue();
							}
							if(entityRechargeRule.getDMode()==12){
								addMoney =  -1 * e.intValue();
							}
							break;
						}
					}
				}else{
					if(entityRechargeRuleFirst.getRecharge()==0){
						//不能充值
						return ResultUtil.error(ResultEnum.Err_3069);
					}
					if(consState==1 && amount.compareTo(entityRechargeRuleFirst.getRecharge())>0){
						//超过自定义最大充值金额
						return ResultUtil.error(ResultEnum.Err_3070);
					}
					BigInteger a=new BigInteger(String.valueOf(entityRechargeRuleFirst.getDValue()));
					BigInteger b=new BigInteger(String.valueOf(100));
					BigInteger c=new BigInteger(String.valueOf(amount));
					BigInteger d=a.multiply(c);
					//舍去取整
					BigInteger e=d.divide(b);

					if(entityRechargeRuleFirst.getDMode()==1){
						addMoney = entityRechargeRuleFirst.getDValue();
					}
					if(entityRechargeRuleFirst.getDMode()==2){
						addMoney = e.intValue();
					}
					if(entityRechargeRuleFirst.getDMode()==3){
						subMoney = entityRechargeRuleFirst.getDValue();
					}
					if(entityRechargeRuleFirst.getDMode()==4){
						subMoney = e.intValue();
					}
					if(entityRechargeRuleFirst.getDMode()==11){
						addMoney = -1 *  entityRechargeRuleFirst.getDValue();
					}
					if(entityRechargeRuleFirst.getDMode()==12){
						addMoney =  -1 * e.intValue();
					}
				}
			}
		}catch (Exception e){
			log.info("计算公众号充值规则异常 【{}】",e);
		}

		Integer ChargeMoney = amount + addMoney;


		EntityXfRecordProcess entityXfRecordProcess =new EntityXfRecordProcess();
		entityXfRecordProcess.setComId(userInfo.getComId());
		entityXfRecordProcess.setDeviceNo("00000000");
		entityXfRecordProcess.setDeviceName("公众号充值H5");
		entityXfRecordProcess.setPointId(0l);
		entityXfRecordProcess.setPName(xfUserInfoVo.getPName());
		entityXfRecordProcess.setMerchId(entityXfMerchantInfo.getMerchId().longValue());
		entityXfRecordProcess.setMerchName(entityXfMerchantInfo.getMerchName());
		entityXfRecordProcess.setDeptId(xfUserInfoVo.getDeptId());
		entityXfRecordProcess.setDeviceName("");
		entityXfRecordProcess.setPId(userInfo.getPId());
		entityXfRecordProcess.setPCode(xfUserInfoVo.getPCode());
		entityXfRecordProcess.setDeptName(xfUserInfoVo.getDeptName());
		entityXfRecordProcess.setAccountNo(xfUserInfoVo.getAccountNo());
		entityXfRecordProcess.setCardNo("");
		entityXfRecordProcess.setChargeBalance(xfUserInfoVo.getChargeBalance().longValue()+amount.longValue());
		entityXfRecordProcess.setSubBalance(0l);
		entityXfRecordProcess.setConsTime(new Date());
		entityXfRecordProcess.setMealDate(new Date());
		entityXfRecordProcess.setMealNo("");
		entityXfRecordProcess.setDiscount(0l);
		entityXfRecordProcess.setConsMoney(amount.longValue());
		entityXfRecordProcess.setRealMoney(amount.longValue());
		entityXfRecordProcess.setChargeMoney(ChargeMoney.longValue());
		entityXfRecordProcess.setSubMoney(subMoney.longValue());
		entityXfRecordProcess.setConsState(consStateType);
		entityXfRecordProcess.setOpType(12l);
		entityXfRecordProcess.setPayChannelNo(entityXfMerchantInfo.getCompanyId());
		entityXfRecordProcess.setPayAmount(ChargeMoney.longValue());
		entityXfRecordProcess.setSubAccount(subAccount);
		if(type==1){
			entityXfRecordProcess.setOpTypeDiff(201l);
			entityXfRecordProcess.setPayWay(1);
		}
		if(type==2){
			entityXfRecordProcess.setOpTypeDiff(204l);
			entityXfRecordProcess.setPayWay(7);
		}
		if(type==3 || type==10){
			entityXfRecordProcess.setOpTypeDiff(201l);
			entityXfRecordProcess.setPayWay(14);
		}
		if(type==4){
			entityXfRecordProcess.setOpTypeDiff(309l);
			entityXfRecordProcess.setPayWay(30);
		}
		if(type==5){
			entityXfRecordProcess.setOpTypeDiff(201l);
			entityXfRecordProcess.setPayWay(7);
		}
		if(type==6){
			entityXfRecordProcess.setOpTypeDiff(201l);
			entityXfRecordProcess.setPayWay(6);
		}
		if(type==12){
			entityXfRecordProcess.setOpTypeDiff(Long.valueOf(OpTypeDiffEnum.LanZhouPay.getIndex()));
			entityXfRecordProcess.setPayWay(37);
		}
		if(type==11){
			entityXfRecordProcess.setOpTypeDiff(Long.valueOf(OpTypeDiffEnum.ZhongXin.getIndex()));
			entityXfRecordProcess.setPayWay(33);
		}
		if(type==13){
			entityXfRecordProcess.setOpTypeDiff(Long.valueOf(OpTypeDiffEnum.YingSheng.getIndex()));
			entityXfRecordProcess.setPayWay(34);
		}
//		System.out.println(entityXfRecordProcess);

//		//雪花Id
//		Integer workId=(Integer)redisUtil.hmGet("Snowflake:workerId:process", IPUtils.getLocalPort());
//		if(workId==null){
//			Long nowWorkId=redisUtil.incr("Snowflake:workerId:process:incr",1l);
//			if(nowWorkId>28){
//				redisUtil.del("Snowflake:workerId:process:incr");
//				redisUtil.del("Snowflake:workerId:process");
//				nowWorkId=redisUtil.incr("Snowflake:workerId:incr",1l);
//			}
//			workId=nowWorkId.intValue();
//			redisUtil.hmSet("Snowflake:workerId:process",IPUtils.getLocalPort(),workId);
//		}
//		SnowflakeIdWorker snowflakeIdWorker=  new SnowflakeIdWorker(workId,5,workId);
//
//		String ord =  Long.toString(snowflakeIdWorker.nextId());
		String ord = RandomUtil.generateNumber(8);
//		String ord = "00000000";
		Date date= new Date();
		String orderTime = DateUtils.getStrDate(date,DateUtils.YYYYMMDDHHMMSS) ;

		String orderNo2 = ord+orderTime;

		orderNo2 = prefix + NumConvertUtil.IntToHexStringNum(userInfo.getComId().intValue(),6) + orderNo2 ;
		entityXfRecordProcess.setPlatOrderNo(orderNo2);
		entityXfRecordProcess.setOrderNo(orderNo2);


		entityXfRecordProcess.setChannelOrderNo("");
		entityXfRecordProcess.setOrigOrderNo("");
		entityXfRecordProcess.setIfRefund(0l);
		entityXfRecordProcess.setPayTime(null);
		entityXfRecordProcess.setPayState(0);
		entityXfRecordProcess.setPayAmount(0l);
		entityXfRecordProcess.setRefundTime(null);
		entityXfRecordProcess.setDiscountWay(0);
		entityXfRecordProcess.setChannelDiscount(0);

		entityXfRecordProcess.setReserved2(String.valueOf(feeDataId));//缴费单id

		entityXfRecordProcess.setMonthValue(DateUtils.getStrDate(date,"yyyyMM"));
		entityXfRecordProcess.setCreateTime(new Date());

		Result result12 = payHandleClientService.preOrder(entityXfRecordProcess);
		if(result12.getCode()!=200){
			return result12;
		}
		//获取请求ip地址

		Map<String,Object> map =new HashMap<>();
		map.put("comId", userInfo.getComId());
		map.put("totalFee",amount);

		//3.公众号发起支付参数  统一支付与下单模式
		//3.公众号发起支付参数  统一支付与下单模式

		String url = getPayCenterUrl(userInfo.getComId(),entityXfMerchantInfo.getCompanyId());

		//返回的type 1 公众号支付 2跳转url  3页面post跳转 4拿订单号跳小程序  5 虚拟账户和代扣直接提示 7订餐虚拟账户或者金额0直接提示


		//3.随行付公众号发起支付参数  统一支付与下单模式
		if(type == 1){
			String RealUrl=url+"unifiedpreorder/lordesau.do";

			Map<String,Object> stringObjectMap =new HashMap<>();
			stringObjectMap.put("company_id",entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password",entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name",entityXfMerchantInfo.getUserName());
//
//			stringObjectMap.put("company_id","20211210001");
//			stringObjectMap.put("user_name","DianZi");
//			stringObjectMap.put("password","123456");


			stringObjectMap.put("pos_no","00000000");
			stringObjectMap.put("devsnip","127.0.0.1");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
			stringObjectMap.put("subject","余额充值");
			stringObjectMap.put("total_amount",amount);
			stringObjectMap.put("fee_type","CNY");
			stringObjectMap.put("trade_type","JSAPI");
			stringObjectMap.put("payway",3);
			stringObjectMap.put("body",userInfo.getComId().toString());
			stringObjectMap.put("operator","admin");
			stringObjectMap.put("openid",userInfo.getOpenId());
//		stringObjectMap.put("notify_url","");

			RequestUtil requestUtil=new RequestUtil();

			log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

			Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

			Result result3 = gson.fromJson(gson.toJson(re),Result.class);

			log.info("返回【{}】  ",result3);
			log.info("z支付url【{}】  ",url);


			if(result3 == null || result3.getCode()!=200){
				return ResultUtil.info(result3.getCode(),result3.getMsg(),result3.getData());
				/**
				 Map<String,Object> map =new HashMap<>();
				 map.put("outTradeNo","nrFqKJYvQooEtXdTXVKKHVPkkgXxj3Lq");
				 map.put("timeStamp","1657084272");
				 map.put("nonceStr","B7RhLtRQ5XkpLk0h");
				 map.put("appid","wx7b35e13388684b68");
				 map.put("sign","E315466DA8AFD4709DED09A3BB6A0568");
				 map.put("mchId","1483737272");
				 map.put("prepayId","wx06131112573065de8b46e350ebafdc0000");
				 return ResultUtil.success(map);
				 **/
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
			JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));


			log.info("微信下单返回【{}】",jsonObject);

			map.put("outTradeNo",jsonObject.getString("out_trade_no"));
			map.put("timeStamp",jsonObject1.getString("timeStamp"));
			map.put("nonceStr",jsonObject1.getString("nonce_str"));
			map.put("appid",jsonObject1.getString("appid"));
			map.put("sign",jsonObject1.getString("sign"));
			map.put("mchId",jsonObject1.getString("mch_id"));
			map.put("signType",jsonObject1.getString("signType"));

			if(CommonUtil.isNull(jsonObject1.getString("signType"))){
				map.put("signType","MD5");
			}

			if(CommonUtil.isNull(jsonObject1.getString("appid"))){
				map.put("appid",jsonObject1.getString("appId"));
			}
			if(CommonUtil.isNull(jsonObject1.getString("nonce_str"))){
				map.put("nonceStr",jsonObject1.getString("nonceStr"));
			}
			if(CommonUtil.isNull(jsonObject1.getString("sign"))){
				map.put("sign",jsonObject1.getString("paySign"));
			}

			String prepayId  = jsonObject1.getString("prepay_id");
			if(CommonUtil.isNull(jsonObject1.getString("prepay_id"))){
				prepayId  = jsonObject1.getString("package");
			}

			map.put("mchId",jsonObject1.getString("mch_id"));

			if(prepayId!=null && prepayId.startsWith("prepay_id=")){
				prepayId=prepayId.substring(10);
			}
			map.put("prepayId",prepayId);
			map.put("type",1);
		}

		//3.微信官方公众号发起支付参数  统一支付与下单模式
		if(type == 3  ||  type == 13 ){
			String RealUrl=url+"unifiedpreorder/lordesau.do";

			Map<String,Object> stringObjectMap =new HashMap<>();
			stringObjectMap.put("company_id",entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password",entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name",entityXfMerchantInfo.getUserName());
//
//			stringObjectMap.put("company_id","20211210001");
//			stringObjectMap.put("user_name","DianZi");
//			stringObjectMap.put("password","123456");


			stringObjectMap.put("pos_no","00000000");
			stringObjectMap.put("devsnip","127.0.0.1");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
			stringObjectMap.put("subject","余额充值");
			stringObjectMap.put("total_amount",amount);
			stringObjectMap.put("fee_type","CNY");
			stringObjectMap.put("trade_type","JSAPI");
//			stringObjectMap.put("pay_way",3);
			stringObjectMap.put("payway",3);
			stringObjectMap.put("body",userInfo.getComId().toString());
			stringObjectMap.put("operator","admin");
			stringObjectMap.put("openid",userInfo.getOpenId());
//		stringObjectMap.put("notify_url","");

			RequestUtil requestUtil=new RequestUtil();

			log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

			Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

			Result result3 = gson.fromJson(gson.toJson(re),Result.class);

			log.info("返回【{}】  ",result3);

			if(result3 == null || result3.getCode()!=200){
				return ResultUtil.info(result3.getCode(),result3.getMsg(),result3.getData());
				/**
				 Map<String,Object> map =new HashMap<>();
				 map.put("outTradeNo","nrFqKJYvQooEtXdTXVKKHVPkkgXxj3Lq");
				 map.put("timeStamp","1657084272");
				 map.put("nonceStr","B7RhLtRQ5XkpLk0h");
				 map.put("appid","wx7b35e13388684b68");
				 map.put("sign","E315466DA8AFD4709DED09A3BB6A0568");
				 map.put("mchId","1483737272");
				 map.put("prepayId","wx06131112573065de8b46e350ebafdc0000");
				 return ResultUtil.success(map);
				 **/
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
			JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

			map.put("outTradeNo",jsonObject.getString("out_trade_no"));
			String prepayId  = "";

			map.put("appid",jsonObject.getString("payAppId"));
			if(jsonObject1!=null){
				map.put("timeStamp",jsonObject1.getString("timeStamp"));
				map.put("nonceStr",jsonObject1.getString("nonce_str"));
				map.put("appid",jsonObject1.getString("appid"));
				map.put("sign",jsonObject1.getString("sign"));
				map.put("mchId",jsonObject1.getString("mch_id"));
				map.put("signType",jsonObject1.getString("signType"));
				map.put("mchId",jsonObject1.getString("mch_id"));


				if(CommonUtil.isNull(jsonObject1.getString("signType"))){
					map.put("signType","MD5");
				}
				if(!CommonUtil.isNull(jsonObject1.getString("appid"))){
					map.put("appid",jsonObject1.getString("appId"));
				}
				if(!CommonUtil.isNull(jsonObject1.getString("nonce_str"))){
					map.put("nonceStr",jsonObject1.getString("nonceStr"));
				}
				if(!CommonUtil.isNull(jsonObject1.getString("sign"))){
					map.put("sign",jsonObject1.getString("paySign"));
				}
				 prepayId  = jsonObject1.getString("prepay_id");

				if(CommonUtil.isNull(jsonObject1.getString("prepay_id"))){
					prepayId  = jsonObject1.getString("package");
				}
			}

			if(!CommonUtil.isNull(jsonObject.getString("paySignType"))){
				map.put("signType",jsonObject.getString("paySignType"));
			}

			if(!CommonUtil.isNull(jsonObject.getString("payAppId"))){
				map.put("appid",jsonObject.getString("payAppId"));
			}

			if(!CommonUtil.isNull(jsonObject.getString("paynonceStr"))){
				map.put("nonceStr",jsonObject.getString("paynonceStr"));
			}

			if(!CommonUtil.isNull(jsonObject.getString("paySign"))){
				map.put("sign",jsonObject.getString("paySign"));
			}

			if(!CommonUtil.isNull(jsonObject.getString("payPackage"))){
				prepayId  = jsonObject.getString("payPackage");
			}
			if(prepayId!=null && prepayId.startsWith("prepay_id=")){
				prepayId=prepayId.substring(10);
			}
			map.put("prepayId",prepayId);

			if(!CommonUtil.isNull(jsonObject.getString("ordNo"))){
				map.put("outTradeNo",jsonObject.getString("ordNo"));
			}

			if(!CommonUtil.isNull(jsonObject.getString("payTimeStamp"))){
				map.put("timeStamp",jsonObject.getString("payTimeStamp"));
			}

			map.put("type",1);
		}

		//建行H5
		if(type ==2){
			String RealUrl=url+"unifiedpreorder/lordesau.do";

			Map<String,Object> stringObjectMap =new HashMap<>();
			stringObjectMap.put("company_id",entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password",entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name",entityXfMerchantInfo.getUserName());
//			stringObjectMap.put("company_id","20211210001");
//			stringObjectMap.put("user_name","DianZi");
//			stringObjectMap.put("password","123456");

			stringObjectMap.put("pos_no","00000000");
			stringObjectMap.put("devsnip","127.0.0.1");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
			stringObjectMap.put("subject","数字人民币充值");
			stringObjectMap.put("total_amount",amount);
			stringObjectMap.put("fee_type","CNY");
			stringObjectMap.put("trade_type","MWEB");
			stringObjectMap.put("pay_way",15);
			stringObjectMap.put("payway",15);
			stringObjectMap.put("body",userInfo.getComId().toString());
			stringObjectMap.put("operator","admin");
//			stringObjectMap.put("openid",userInfo.getOpenId());

			RequestUtil requestUtil=new RequestUtil();

			log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

			Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

			Result result3 = gson.fromJson(gson.toJson(re),Result.class);
			if(result3.getCode()!=200){
				return result3;
			}

			JSONObject  jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));


			map.put("type",2);
			map.put("code_url",jsonObject.get("code_url"));

			log.info("数字人民币返回【{}】  ",map);
			return ResultUtil.success(map);
		}

		//招行一网通
		if(type == 4){
			String RealUrl=url+"unifiedpreorder/lordesau.do";

			Map<String,Object> stringObjectMap =new HashMap<>();
			stringObjectMap.put("company_id",entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password",entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name",entityXfMerchantInfo.getUserName());
//
			stringObjectMap.put("body","支付回调返回");
			stringObjectMap.put("subject","签约回调返回");

			stringObjectMap.put("pos_no","00000000");
			stringObjectMap.put("devsnip","192.168.11.250");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
//			stringObjectMap.put("subject","余额充值");
			stringObjectMap.put("total_amount",amount);
			stringObjectMap.put("fee_type","CNY");
			stringObjectMap.put("trade_type","JSAPI");
			stringObjectMap.put("payway",30);
//			stringObjectMap.put("body",userInfo.getComId().toString());

			stringObjectMap.put("operator","admin");


			String signNo = MD5.MD5Encode(userInfo.getOpenId(),"utf8");
			stringObjectMap.put("openid",signNo);
//		stringObjectMap.put("notify_url","");

			RequestUtil requestUtil=new RequestUtil();

			log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

			Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

			Result result3 = gson.fromJson(gson.toJson(re),Result.class);

			log.info("返回【{}】  ",result3);

			if(result3 == null || result3.getCode()!=200){
				return ResultUtil.info(result3.getCode(),result3.getMsg(),result3.getData());
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
			map.put("params",JSON.parseObject(jsonObject.getString("prepay_id")));
			map.put("type",3);
			map.put("code_url",jsonObject.get("code_url"));
		}

		//建行公众号
		if(type == 5){
			String RealUrl=url+"unifiedpreorder/lordesau.do";

			Map<String,Object> stringObjectMap =new HashMap<>();
			stringObjectMap.put("company_id",entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password",entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name",entityXfMerchantInfo.getUserName());


			stringObjectMap.put("pos_no","00000000");
			stringObjectMap.put("devsnip","127.0.0.1");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
			stringObjectMap.put("subject","余额充值");
			stringObjectMap.put("total_amount",amount);
			stringObjectMap.put("fee_type","CNY");
			stringObjectMap.put("trade_type","JSAPI");

			stringObjectMap.put("payway",7);
			stringObjectMap.put("body",userInfo.getComId().toString());
			stringObjectMap.put("operator","admin");
			stringObjectMap.put("openid",userInfo.getOpenId());
//		stringObjectMap.put("notify_url","");

			RequestUtil requestUtil=new RequestUtil();

			log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);

			Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));

			Result result3 = gson.fromJson(gson.toJson(re),Result.class);

			log.info("返回【{}】  ",result3);

			if(result3 == null || result3.getCode()!=200){
				return ResultUtil.info(result3.getCode(),result3.getMsg(),result3.getData());
				/**
				 Map<String,Object> map =new HashMap<>();
				 map.put("outTradeNo","nrFqKJYvQooEtXdTXVKKHVPkkgXxj3Lq");
				 map.put("timeStamp","1657084272");
				 map.put("nonceStr","B7RhLtRQ5XkpLk0h");
				 map.put("appid","wx7b35e13388684b68");
				 map.put("sign","E315466DA8AFD4709DED09A3BB6A0568");
				 map.put("mchId","1483737272");
				 map.put("prepayId","wx06131112573065de8b46e350ebafdc0000");
				 return ResultUtil.success(map);
				 **/
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
			JSONObject jsonObject1 = JSON.parseObject(jsonObject.getString("prepay_id"));

			//jsonObject1 判断
//			if(result3 == null || result3.getCode()!=200) {
//				return ResultUtil.info(result3.getCode(), result3.getMsg(), result3.getData());
//			}

			map.put("outTradeNo",jsonObject.getString("out_trade_no"));
			map.put("timeStamp",jsonObject1.getString("timeStamp"));
			map.put("nonceStr",jsonObject1.getString("nonceStr"));
			map.put("appid",jsonObject1.getString("appId"));
			map.put("sign",jsonObject1.getString("paySign"));
			map.put("signType",jsonObject1.getString("signType"));
			String prepayId  = jsonObject1.getString("package");
			if(prepayId!=null && prepayId.startsWith("prepay_id=")){
				prepayId=prepayId.substring(10);
			}
			map.put("prepayId",prepayId);
			map.put("type",1);
		}

		//收钱吧 跳转支付
		if(type == 6) {
			String RealUrl = url + "unifiedpreorder/lordesau.do";

			Map<String, Object> stringObjectMap = new HashMap<>();
			stringObjectMap.put("company_id", entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password", entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name", entityXfMerchantInfo.getUserName());
			stringObjectMap.put("pos_no", "00000000");
			stringObjectMap.put("devsnip", "192.168.11.250");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
			stringObjectMap.put("subject", "Recharge");
			stringObjectMap.put("total_amount", amount);
			stringObjectMap.put("fee_type", "CNY");
			stringObjectMap.put("trade_type", "MWEB-JUMP");
			stringObjectMap.put("payway", 6);
			stringObjectMap.put("operator", "admin");

			stringObjectMap.put("openid", userInfo.getOpenId());

			RequestUtil requestUtil = new RequestUtil();

			log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

			Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

			Result result3 = gson.fromJson(gson.toJson(re), Result.class);
			if (result3.getCode() != 200) {
				return result3;
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));


			map.put("type", 2);
			map.put("code_url", jsonObject.get("code_url"));

//			log.info("收钱吧返回【{}】  ", map);
			return ResultUtil.success(map);
		}
		log.info("返回前端参数【{}】  ",map);
		//4. mq延时查询

		//跳转随行付小程序
		if(type == 10) {
			map.put("type", 4);
			map.put("orderNo", orderNo2);
			return ResultUtil.success(map);
		}

		//中信银行
		if(type == 11){
			String RealUrl=url+"unifiedpreorder/lordesau.do";

			Map<String,Object> stringObjectMap =new HashMap<>();
			stringObjectMap.put("company_id",entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password",entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name",entityXfMerchantInfo.getUserName());


			stringObjectMap.put("pos_no","00000000");
			stringObjectMap.put("devsnip","127.0.0.1");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
			stringObjectMap.put("subject","Recharge");
			stringObjectMap.put("total_amount",amount);
			stringObjectMap.put("fee_type","CNY");
			stringObjectMap.put("trade_type","JSAPI");
			stringObjectMap.put("payway",33);
			stringObjectMap.put("body",userInfo.getComId().toString());
			stringObjectMap.put("operator","admin");
			stringObjectMap.put("openid",userInfo.getOpenId());
			stringObjectMap.put("longitude","106.292233");
			stringObjectMap.put("latitude","29.602254");
//			106.29,29.60
////		stringObjectMap.put("notify_url","");
//
			RequestUtil requestUtil=new RequestUtil();
//
			log.info("地址【{}】  参数【{}】",RealUrl,stringObjectMap);
//
			Map<String, String> re = requestUtil.doPostJson(RealUrl,JSON.toJSONString(stringObjectMap));
//
			Result result3 = gson.fromJson(gson.toJson(re),Result.class);
//
			log.info("返回【{}】  ",result3);

			if(result3 == null || result3.getCode()!=200){
				return ResultUtil.info(result3.getCode(),result3.getMsg(),result3.getData());
			}
//
			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));
			map.put("type", 3);
			map.put("params", jsonObject.get("params"));
			map.put("code_url", jsonObject.getString("code_url"));
		}


		if(type == 12) {
			String RealUrl = url + "unifiedpreorder/lordesau.do";

			Map<String, Object> stringObjectMap = new HashMap<>();
			stringObjectMap.put("company_id", entityXfMerchantInfo.getCompanyId());
			stringObjectMap.put("password", entityXfMerchantInfo.getPassword());
			stringObjectMap.put("user_name", entityXfMerchantInfo.getUserName());
			stringObjectMap.put("pos_no", "00000000");
			stringObjectMap.put("devsnip", "192.168.11.250");
			stringObjectMap.put("out_trade_no", entityXfRecordProcess.getPlatOrderNo());
			stringObjectMap.put("subject", "Recharge");
			stringObjectMap.put("body", "Recharge");
			stringObjectMap.put("total_amount", amount);
			stringObjectMap.put("payway", 37);
			stringObjectMap.put("openid", userInfo.getOpenId());

			RequestUtil requestUtil = new RequestUtil();

			log.info("地址【{}】  参数【{}】", RealUrl, stringObjectMap);

			Map<String, String> re = requestUtil.doPostJson(RealUrl, JSON.toJSONString(stringObjectMap));

			Result result3 = gson.fromJson(gson.toJson(re), Result.class);
			if (result3.getCode() != 200) {
				return result3;
			}

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result3.getData()));


			map.put("type", 2);
			map.put("code_url", jsonObject.get("code_url"));

//			log.info("收钱吧返回【{}】  ", map);
//			return ResultUtil.success(map);
		}

		CheckVo checkVo=new CheckVo();
		checkVo.setMachNo("00000000");
		checkVo.setCompanyId(userInfo.getComId());
		checkVo.setOutTradeNo(entityXfRecordProcess.getPlatOrderNo() );
		activeQuiryProduct.sendDelayMessage( gson.toJson(checkVo));

		log.info("公众号参数 【{}】【{}】", entityXfRecordProcess.getPlatOrderNo(),map);

		return ResultUtil.success(map);
	}

	//接收回调de实际操作
	@Override
	public Boolean callback(Result result) {
		//执行单库事务

		/**
		 * {
		 * 	"msg": "success",
		 * 	"code": 200,
		 * 	"data": {
		 * 		"body": "19045953,273,46,1785",
		 * 		"out_trade_no": "2020071310543436819045953",
		 * 		"time_end": "20200713105505",
		 * 		"total_amount": "1",
		 * 		"trade_no": "20200713105436590054",
		 * 		"trade_status": "SUCCESS",
		 * 		"trade_type": "weixin"
		 *        }
		 * }
		 */

		Gson gson=new Gson();

		if(result.getCode()==200){
			Map<String , String >  map = gson.fromJson(gson.toJson(result.getData()),Map.class);
			if(map.get("trade_status").equals("SUCCESS")){
				//插入限流队列
				Long comId = 0l ;
				if(map.get("out_trade_no").startsWith("CART")){
					comId = NumConvertUtil.HexStringToInt(map.get("out_trade_no").substring(4,10)).longValue();
				}else{
					comId = NumConvertUtil.HexStringToInt(map.get("out_trade_no").substring(2,8)).longValue();
				}
//				String deviceNo = map.get("out_trade_no").substring(8,16);
				CallBackVo callBackVo=new CallBackVo();
				callBackVo.setCompanyId(comId);
				callBackVo.setPlatOrderNo(map.get("out_trade_no"));
				callBackVo.setPayTime(map.get("time_end"));
				callBackVo.setStatus(1);
//				callBackVo.setMachNo(deviceNo);
				callbackProducer.sendLimitingMessage(gson.toJson(callBackVo));
			}
		}


		//执行跨库补单推送



		return true;
	}

	@Override
	public void check(Long companyId,String outTradeNo) {
//		String chekUrl = url+"unifiedmicropay/select.do";

		Map<String,Object> stringObjectMap =new HashMap<>();


//		stringObjectMap.put("company_id","20211210001");
//		stringObjectMap.put("password","123456");
//		stringObjectMap.put("user_name","DianZi");

		//1、获取支付通道
//		Result result = payConfigClientService.MerchPageInfo(companyId, 0);
//		log.info("公众号支付-获取支付通道参数 【{}】",result);
//		if(result.getCode()!=200){
//			log.info("支付参数获取失败 【{}】【{}】【{}】 ",companyId,outTradeNo, result);
//			return;
//		}
		Result result = null;
//		if(CommonUtil.isNull(machNo) || machNo.equals("0000")){
//			result = payHandleClientService.getUsefuleMerchPayInfo(companyId,"");
//		}else{
//			result = payHandleClientService.getUsefuleMerchPayInfo(companyId,"");
////		}
//		log.info("公众号支付-获取支付通道参数 【{}】【{}】【{}】",companyId,"machNo",result);
//		if(result.getCode()!=200){
//			log.info("支付参数获取失败 【{}】【{}】【{}】【{}】 ",companyId,"machNo",outTradeNo, result);
//			return;
//		}
//
////		EntityXfMerchantInfo entityXfMerchantInfo = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),EntityXfMerchantInfo.class);
//
//		EntiyXfMerchPayInfo entiyXfMerchPayInfo = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),EntiyXfMerchPayInfo.class);

		Result orderResult = payHandleClientService.getOrderInfo(companyId, outTradeNo, null);
		if (200 != orderResult.getCode() && null == orderResult.getData()) {
			log.info("公众号支付-获取订单失败 【{}】",orderResult);
		}
		EntityXfRecordProcess entityXfRecordProcess = JSON.parseObject(JSON.toJSONString(orderResult.getData()), EntityXfRecordProcess.class);

		Integer merchId = entityXfRecordProcess.getMerchId().intValue();
		Result result6 = companyClientService.getCompanyConfig(companyId,"gzhOcom");
		if(result6.getCode()==200) {
			List<EntityCompanyConfig> companyConfigList = JSON.parseArray(JSON.toJSONString(result6.getData()), EntityCompanyConfig.class);
			if(companyConfigList !=null && companyConfigList.size()>0
					&& companyConfigList.get(0).getConfig().equals("true")){
				merchId = 0 ;
			}
		}
		result = payConfigClientService.MerchPageInfo(companyId, merchId);
		log.info("公众号支付-获取支付通道参数 【{}】",result);
		if(result.getCode()!=200){
			log.info("支付参数获取失败 【{}】 ", result);
//			return ResultUtil.error(ResultEnum.Err_4023);
		}


		EntityXfMerchantInfo entityXfMerchantInfo = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),EntityXfMerchantInfo.class);

		stringObjectMap.put("company_id",entityXfMerchantInfo.getCompanyId());
		stringObjectMap.put("password",entityXfMerchantInfo.getPassword());
		stringObjectMap.put("user_name",entityXfMerchantInfo.getUserName());


//		stringObjectMap.put("company_id","20211210001");
//		stringObjectMap.put("user_name","DianZi");
//		stringObjectMap.put("password","123456");

		stringObjectMap.put("pos_no","00000000");
		stringObjectMap.put("out_trade_no",outTradeNo);

		RequestUtil requestUtil=new RequestUtil();

		String url = getPayCenterUrl(companyId, entityXfMerchantInfo.getCompanyId());
		String chekUrl = url+"unifiedmicropay/select.do";

		Map re= requestUtil.doPostMap(chekUrl,stringObjectMap);


		Gson gson=new Gson();
		RespMachMessage result1 = gson.fromJson(gson.toJson(re),RespMachMessage.class);

		log.info("公众号支付  2iMRVAvx  -mq获取订单状态 【{}】【{}】",stringObjectMap,result1);

		try {
			if (result1.getCode().equals("200")) {
				Map<String, String> map = gson.fromJson(gson.toJson(result1.getData()), Map.class);
				// NOTPAY     SUCCESS
				//订单 查询
				if (map.get("trade_status").equals("SUCCESS")) {
					//成功
					CallBackVo callBackVo = new CallBackVo();
					callBackVo.setCompanyId(companyId);
					callBackVo.setPlatOrderNo(outTradeNo);
					callBackVo.setPayTime(map.get("time_end"));
					callBackVo.setStatus(1);


					payHandleClientService.callback(callBackVo);


					Result result3 = payHandleClientService.getOrderInfo(callBackVo.getCompanyId(), callBackVo.getPlatOrderNo(), "");
					//同步到成功记录
					if (result3.getCode() == 200) {
						EntityXfRecord entityXfRecord = JSONObject.parseObject(JSON.toJSONString(result3.getData()), EntityXfRecord.class);
						entityXfRecord.setPayState(1);
						Result result4 = xfRecodeClientService.sveXfRecord(entityXfRecord);
						if (entityXfRecord.getConsType() == 100) {
							payHandleClientService.syncSaveGoodList(entityXfRecord.getComId(), entityXfRecord.getOrderNo());
						}
						log.info("记录到成功库 【{}】【{}】", callBackVo, result4);

						//视频话机发放套餐
						if (3 == entityXfRecordProcess.getConsType() || 5 == entityXfRecordProcess.getConsType()) {
							try {
								AddPackagePayRequest addPackagePayRequest = new AddPackagePayRequest();
								addPackagePayRequest.setComId(entityXfRecordProcess.getComId());
								addPackagePayRequest.setPId(entityXfRecordProcess.getPId());
								addPackagePayRequest.setPackageTypeId(Long.valueOf(entityXfRecordProcess.getReserved1()));
								addPackagePayRequest.setStartDate(entityXfRecordProcess.getMealDate());
								payConfigClientService.addPackagePay(addPackagePayRequest);
							} catch (Exception e) {
								e.printStackTrace();
								log.info("视频话机发放套餐异常 【{}】【{}】", callBackVo, result);
							}
						}
					} else {
						//记录异常
						log.info("获取订单异常 【{}】【{}】", callBackVo, result);
					}
				}
			}
		}catch (Exception exception){
			log.info("公众号CHeck 处理异常 vAdJTsz4 【{}】",exception);
		}
		
		//避免重复缴费的处理  2025-5-24 15:54:39 zhuhui
		if(entityXfRecordProcess.getConsState() == 111){
			//查询次数
			String receiptNoKey = "gzhCheck:" + outTradeNo;
			Long times = redisUtil.incr(receiptNoKey, 1l);
			redisUtil.expire(receiptNoKey, 60 * 60l);

			String unlockKey = "feeDataPayLock#comId:" + companyId + "#feeDataId:" + entityXfRecordProcess.getReserved2();

			if (result1.getCode().equals("21") && times > 1l) {
				//订单不存在
				//支付失败
				redisUtil.unlock(unlockKey);
			}
			if (result1.getCode().equals("200")){
				Map<String , String >  dataMap = gson.fromJson(gson.toJson(result1.getData()),Map.class);
				if (dataMap.get("trade_status").equals("PAYERROR") ||
						dataMap.get("trade_status").equals("REVOKED") || dataMap.get("trade_status").equals("CLOSED")
						|| dataMap.get("trade_status").equals("REFUND")) {
					//支付失败
					if (times > 1l) {
						//支付失败
						redisUtil.unlock(unlockKey);
					}
				}
			}
		}

//		log.info("998877");

	//RespMachMessage{code='200', msg='success', data={out_trade_no=20220708155802944179859074191360, trade_status=NOTPAY, trade_state_desc=订单未支付}}
	//{msg=success, code=200, data={"out_trade_no":"20220708155651944179559022071808","total_amount":"1","trade_status":"SUCCESS","trade_no":"4200001518202207085318442758","trade_type":"pay.weixin.preorder","pay_code_type":"","time_end":"20220708155658","body":"说明"}}

	}

	@Override
	public void serviceCharges(ServiceChargesVo serviceChargesVo) {
		log.info("公众号查询服务费-开始处理 【{}】",serviceChargesVo);
		String url = getPayCenterUrl(serviceChargesVo.getComId(), serviceChargesVo.getCompanyId());
		String chekUrl = url+"unifiedmicropay/select.do";

		Map<String,Object> stringObjectMap =new HashMap<>();

		Result result = null;

		Result orderResult = payHandleClientService.getOrderInfo(serviceChargesVo.getComId(), serviceChargesVo.getTradeNo(), null);
		if (200 != orderResult.getCode() && null == orderResult.getData()) {
			log.info("公众号查询服务费-获取订单失败 【{}】",orderResult);
		}
		EntityXfRecordProcess entityXfRecordProcess = JSON.parseObject(JSON.toJSONString(orderResult.getData()), EntityXfRecordProcess.class);

//		result = payConfigClientService.MerchPageInfo(companyId, entityXfRecordProcess.getMerchId().intValue());
//		log.info("公众号查询服务费-获取支付通道参数 【{}】",result);
//		if(result.getCode()!=200){
//			log.info("支付参数获取失败 【{}】 ", result);
//		}
//
//		EntityXfMerchantInfo entityXfMerchantInfo = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),EntityXfMerchantInfo.class);

		stringObjectMap.put("company_id",serviceChargesVo.getCompanyId());
		stringObjectMap.put("password",serviceChargesVo.getPassword());
		stringObjectMap.put("user_name",serviceChargesVo.getUserName());

		stringObjectMap.put("pos_no","000000");
		stringObjectMap.put("out_trade_no",serviceChargesVo.getTradeNo());

		RequestUtil requestUtil=new RequestUtil();
		Map re= requestUtil.doPostMap(chekUrl,stringObjectMap);

		Gson gson=new Gson();
		RespMachMessage result1 = gson.fromJson(gson.toJson(re),RespMachMessage.class);

		log.info("公众号查询服务费-mq获取订单状态 【{}】",result1);

		if(result1.getCode().equals("200")){
			Map<String , String >  map = gson.fromJson(gson.toJson(result1.getData()),Map.class);

			if(map.get("trade_status").equals("SUCCESS")){
				//成功
				String serviceCharges = map.get("channel_fee");
				String realPay = map.get("real_pay");
				String totalAmount = map.get("total_amount");
				if (StringUtils.isNotBlank(serviceCharges) || !CommonUtil.isNull(realPay)) {
					EntityXfRecord entityXfRecord=  JSONObject.parseObject(JSON.toJSONString(entityXfRecordProcess), EntityXfRecord.class);
					if(StringUtils.isNotBlank(serviceCharges)){
						entityXfRecord.setChannelFee(Integer.valueOf(serviceCharges));
					}
					if(!CommonUtil.isNull(realPay)){
						Integer realPay1 = Integer.valueOf(realPay);
						Integer totalAmount1 = Integer.valueOf(totalAmount);
						entityXfRecord.setChannelDiscount(realPay1 - totalAmount1);
					}
					Result result4 = xfRecodeClientService.updateXfRecord(entityXfRecord);
					log.info("公众号查询服务费-更新订单状态 【{}】",result4);
				}
			}else{
				log.info("获取订单异常 【{}】",result);
			}
		}
	}


	//签约接收回调de实际操作
	@Override
	public Boolean callback1(Result result) {
		//执行单库事务

		/**
		 * {
		 * 	"msg": "success",
		 * 	"code": 200,
		 * 	"data": {
		 * 		"body": "19045953,273,46,1785",
		 * 		"out_trade_no": "2020071310543436819045953",
		 * 		"time_end": "20200713105505",
		 * 		"total_amount": "1",
		 * 		"trade_no": "20200713105436590054",
		 * 		"trade_status": "SUCCESS",
		 * 		"trade_type": "weixin"
		 *        }
		 * }
		 */

		Gson gson=new Gson();

		if(result.getCode()==200){
			Map<String , String >  map = gson.fromJson(gson.toJson(result.getData()),Map.class);
			if(map.get("trade_status").equals("SUCCESS")){
				//插入限流队列
				CallBackVo callBackVo=new CallBackVo();
				callBackVo.setCompanyId(Long.valueOf(map.get("body")));
				callBackVo.setPlatOrderNo(map.get("out_trade_no"));
				callBackVo.setStatus(1);
				signProducer.sendLimitingMessage(gson.toJson(callBackVo));
			}
		}
		//执行跨库补单推送
		return true;
	}


	@Override
	public Result staticCodePay(GzhUserInfo userInfo,String code, Integer amount, Integer type,Integer payWay) {
		String openId = userInfo.getOpenId();
		StaticCodePayVo staticCodePayVo = StaticCodePayUtil.getCodeInfo(code);
		if (staticCodePayVo == null) {
			return ResultUtil.error(ResultEnum.Err_3072);
		}
		if(staticCodePayVo.getType()!=1){
			return ResultUtil.error(ResultEnum.Err_3073);
		}
		if(staticCodePayVo.getDeviceNo().length()!=8){
			return ResultUtil.error(ResultEnum.Err_3074);
		}
		StaticCodePayRequest request =new StaticCodePayRequest();
		try {
			String ord = RandomUtil.generateNumber(8);
//			String ord = staticCodePayVo.getDeviceNo();
			Date date= new Date();
			String orderTime = DateUtils.getStrDate(date,DateUtils.YYYYMMDDHHMMSS) ;

			String orderNo2 = ord+orderTime;


			//TODO  单位74以ZS开头 其他以CS开头 （consume）
			String prefix = "CS";
			Result result6 = companyClientService.getCompanyConfig(staticCodePayVo.getComId(),"gzhOcom");
			if(result6.getCode()==200) {
				List<EntityCompanyConfig> companyConfigList = JSON.parseArray(JSON.toJSONString(result6.getData()), EntityCompanyConfig.class);
				if(companyConfigList !=null && companyConfigList.size()>0
						&& companyConfigList.get(0).getConfig().equals("true")){
					prefix = "ZS";
				}
			}

			orderNo2 = prefix + NumConvertUtil.IntToHexStringNum(staticCodePayVo.getComId().intValue(),6) + orderNo2 ;
			request.setCompanyId(staticCodePayVo.getComId());
			request.setAmount(amount);
			request.setMachNo(staticCodePayVo.getDeviceNo());
			request.setOpenId(openId);
			request.setPayWay(payWay);
			request.setType(type);
			request.setTradeNo(orderNo2);
			Result result = payHandleClientService.staticCodePay(request);
			log.info("预下单请求返回 【{}】【{}】",request,result);

			if(result.getCode() ==200 ){

				boolean sendMqttMsg = false ;
				Result result4 = companyClientService.getCompanyConfig(staticCodePayVo.getComId(),"mqttMsg");
				if(result4.getCode()==200) {
					List<EntityCompanyConfig> companyConfigList = JSON.parseArray(JSON.toJSONString(result4.getData()), EntityCompanyConfig.class);
					if(companyConfigList !=null && companyConfigList.size()>0
							&& companyConfigList.get(0).getConfig().equals("true")){
						sendMqttMsg = true ;
					}
				}

				if(sendMqttMsg){
					JSONObject jsonObject =new JSONObject();
					jsonObject.put("companyId",staticCodePayVo.getComId());
					jsonObject.put("machNo",staticCodePayVo.getDeviceNo());
					jsonObject.put("tradeNo",orderNo2);
					jsonObject.put("money", AcpService.stringAmount(amount.toString()));
					emqxClientService.timerQuery(jsonObject);
				}

			}

			if(prefix.equals("ZS")){
				//4. mq延时查询
				Gson gson =new Gson();
				CheckVo checkVo=new CheckVo();
				checkVo.setMachNo(staticCodePayVo.getDeviceNo());
				checkVo.setCompanyId(staticCodePayVo.getComId());
				checkVo.setOutTradeNo(orderNo2);
				activeQuiryProduct.sendDelayMessage( gson.toJson(checkVo));
			}


			return result;
		}catch (Exception e){
			log.info("预下单异常 【{}】",e);
		}


		return ResultUtil.error(ResultEnum.Err_4014);


	}



	@Override
	public String getPayCenterUrl(Long comId, String companyId) {

		if (comId == null) {
			return payCenter.get(0);
		}

		Object payUrl = redisUtil.get("payCenter:#comId:"+comId+"#companyId:" + companyId);
		if (payUrl != null) return payCenter.get((Integer) payUrl);

		if (!payCenterUrl.equals("dev")) {
			if (companyId.length() > 0 && Character.isDigit(companyId.charAt(companyId.length() - 1))) {
				redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 1, Long.valueOf(60 * 60 * 4));
				return payCenter.get(1);
			} else {
				companyId = companyId.toUpperCase(Locale.ROOT);
				char lastChar = companyId.charAt(companyId.length() - 1);
				int indexA = (int) lastChar;
				indexA -= 63;  //A -> 2 B->3 类推
				redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, indexA, Long.valueOf(60 * 60 * 4));
				return payCenter.get(indexA);
			}

		} else {
			redisUtil.set("payCenter:#comId:"+comId+"#companyId:" + companyId, 0, Long.valueOf(60 * 60 * 4));
			return payCenter.get(0);
		}

	}


}
